<template>
	<view class="calender">
		<uni-nav-bar left-icon="left" @clickLeft="back" fixed statusBar="" title="日历记账" :border="false" backgroundColor="#ffcd54" color="#fff"></uni-nav-bar>
		<view class="calender_list dis">
			<view class="calender_bg"></view>
			<view class="calender_year dis_center" @click="selectYear">
				<text class="fs26">{{ year }}</text>
				<view class="calender_pos">
					<view class="triangle triangle_color"></view>
				</view>
			</view>
			<scroll-view class="horizontal-scroll" :scroll-x="true" :scroll-with-animation="true">
				<view class="dis" :style="{ width: `${11 * sonWidth}rpx`, height: '100%' }">
					<view class="calender_month_item fs26" :style="{ width: `${sonWidth}rpx` }" :class="{ itemActive: monthIndex === item }" @click="monthClick(item)" v-for="item in 11" :key="item">{{ `${item + 1}月` }}</view>
				</view>
			</scroll-view>
		</view>
		<view class="p30">
			<view class="chart_box">
				<TabsTotal @tabsClick="tabsClick" :expend="totalExpend" :income="totalIncome"/>
				<view class="chart_echarts">
					<view class="chart_tabs">
						<view class="chart_item" :class="{chart_item_active: chartsType === 'pie' }" @click="chartClick('pie')">
							<text class="iconfont icon-pie-f"></text>
						</view>
						<view class="chart_item" :class="{chart_item_active: chartsType === 'column' }" @click="chartClick('column')">
							<text class="iconfont icon-zhuzhuangtu"></text>
						</view>
					</view>
					<qiun-data-charts :type="chartsType" :opts="opts" :chartData="chartData" />
				</view>
			</view>
			<view class="mt30">
				<view class="dis pl20 pr20 pt30 pb30 progress_box mb20" v-for="item in (tabsIndex === 0 ? tableData : tableList)" :key="item.icon">
					<view style="width: 80rpx;" class="fs28 dis">
						<text :class="['iconfont fs34', item.icon]" style="color: #fe664a;"></text>
					</view>
					<view style="flex: 1;">
						<view class="dis_center_s mb10">
							<view class="fs28">
								<text>{{ item.name }}</text>
								<text class="fs24 text-info ml10">共{{ item.count }}笔</text>
							</view>
							<view class="fs28">
								<text>{{ item.price.toFixed(2) }}</text>
								<text class="ml10">元</text>
							</view>
						</view>
						<progress :percent="calculatePercentage(tabsIndex === 0 ? totalExpend : totalIncome, item.price)" activeColor="#10aeff" stroke-width="3" :show-info="true" />
					</view>
				</view>
			</view>
		</view>
		<PickerView ref="pickerViewRefs" :options="[{ data: itemList }]" @confirm="confirmPicker" :pickerIndex="pickerIndex"/>
	</view>
</template>

<script>
	import PickerView from '@/components/uni-picker-view/index.vue'
	import TabsTotal from './tabs-total.vue'
	import store from '@/store/index.js'
	import { icons } from '@/utils/dict-data.js'
	import { getYearTimes } from '@/utils/common.js'
	const uniTransaction = uniCloud.importObject('transaction')
	export default {
		components: {
			PickerView,
			TabsTotal
		},
		data() {
			return {
				sonWidth: 100,
				year: '',
				monthIndex: 0,
				itemList: [],
				pickerIndex: [0],
				tabsIndex: 0,
				chartData: {},
				opts: {},
				chartsType: 'pie', // pie || column
				totalExpend: 0,
				totalIncome: 0,
				tableData: [],
				tableList: []
			}
		},
		computed: {
			userInfo() {
				return store.state.user.userInfo
			}
		},
		created() {
			const date = new Date()
			this.year = date.getFullYear()
			this.monthIndex = date.getMonth()
			this.initTransaction()
		},
		methods: {
			initTransaction() {
				const queryValue = `${this.year}-${this.zero(this.monthIndex, 1)}`
				uniTransaction.get({ userId: this.userInfo.uid, tallyTime: queryValue }).then(res => {
					const { totalExpend, totalIncome, expendList, incomeList } = this.formatTransaction(res.data)
					this.totalExpend = totalExpend
					this.totalIncome = totalIncome
					this.tableData = expendList
					this.tableList = incomeList
					this.initChart()
				})
			},
			initChart() {
				let res = {}
				let opts = {}
				if(this.chartsType === 'pie') {
					opts = {}
					res = {
						series: [
							{
								data: (this.tabsIndex === 0 ? this.tableData : this.tableList).map(c => ({ name: c.name, value: c.price }))
							}
						]
					}
				} else {
					opts = {
						extra: {
							column: {
								categoryGap: 5
							}
						}
					}
					res = {
						categories: (this.tabsIndex === 0 ? this.tableData : this.tableList).map(c => c.name),
						series: this.tabsIndex === 0 ? [{ name: '支出', data: this.tableData.map(c => ({ value: c.count, color: '#1890ff' })) }] : [{ name: '收入', data: this.tableList.map(c => ({ value: c.count, color: '#91cb74' })) }] 
					}
				}
				this.opts = opts
				this.chartData = res
			},
			chartClick(key) {
				if(this.chartsType === key) return
				this.chartsType = key
				this.initChart()
			},
			back() {
				uni.navigateBack()
			},
			selectYear() {
				this.itemList = getYearTimes()
				this.$refs.pickerViewRefs.open()
			},
			monthClick(item) {
				if(this.monthIndex === item) return
				this.monthIndex = item
				this.initTransaction()
			},
			confirmPicker(event) {
				const value = event.detail.value || event.detail.__args__
				if(this.year === this.itemList[value[0]].label) return
				this.pickerIndex = value
				this.year = this.itemList[value[0]].label
				this.initTransaction()
			},
			zero(value, num = 0) {
				return value < 10 ? '0' + (value + num) : value + num
			},
			tabsClick(index) {
				this.tabsIndex = index
				this.initChart()
			},
			formatTransaction(options) {
				return options.reduce((obj, row) => {
					const flag = ['1', '2'].includes(row.transactionType)
					const find = icons.find(c => c.value === row.icon)
					const expend = flag ? Number(row.amount) : 0
					const income = !flag ? Number(row.amount) : 0
					obj.totalExpend += expend
					obj.totalIncome += income
					if(flag) {
						const index = obj.expendList.findIndex(c => c.icon === row.icon)
						if(index === -1) {
							obj.expendList.push({ icon: row.icon, name: find.text, price: expend, count: 1 })
						} else {
							obj.expendList[index].price += expend
							obj.expendList[index].count += 1
						}
					} else {
						const index = obj.incomeList.findIndex(c => c.icon === row.icon)
						if(index === -1) {
							obj.incomeList.push({ icon: row.icon, name: find.text, price: expend, count: 1 })
						} else {
							obj.incomeList[index].price += expend
							obj.incomeList[index].count += 1
						}
					}
					return obj
				}, { totalExpend: 0, totalIncome: 0, expendList: [], incomeList: [] })
			},
			formatTofixed(value) {
				if(!value) return '0'
				return value.toFixed(2)
			},
			calculatePercentage(current, total) {
			  if (total === 0) {
			    return 0; // 避免除以零的错误
			  }
			  return Math.floor((total / current) * 100)
			}
		}
	}
</script>

<style scoped lang="scss">
	.calender {
		.calender_list {
			position: relative;
			height: 85rpx;
			.calender_bg {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				height: 160rpx;
				z-index: -1;
				background-color: #ffcd54;
			}
			.calender_year {
				position: relative;
				width: 135rpx;
				height: 100%;
				color: #fff;
				.calender_pos {
					position: absolute;
					top: 50%;
					right: -1rpx;
					transform: translateY(-50%);
					color: #fff;
				}
			}
			.horizontal-scroll {
				width: calc(100vw - 135rpx);
				white-space: nowrap;
				display: flex;
				align-items: center;
				height: 100%;
				padding-left: 20rpx;
				.calender_month_item {
					padding: 0 20rpx;
					color: #fff;
					text-align: center;
				}
			}
		}
		.chart_box {
			padding: 30rpx;
			background-color: #fff;
			border-radius: 10rpx;
			box-shadow: 0 0 20rpx 2rpx #ddd;
			.chart_echarts {
				position: relative;
				height: 500rpx;
				padding-top: 40rpx;
				.chart_tabs {
					position: absolute;
					top: 0;
					left: 50%;
					transform: translateX(-50%);
					display: flex;
					align-items: center;
					.chart_item {
						width: 35rpx;
						height: 35rpx;
						border: 1rpx solid #ddd;
						display: flex;
						align-items: center;
						justify-content: center;
						cursor: pointer;
						&:nth-child(1) {
							border-right: 0;
						}
						>.iconfont {
							font-size: 24rpx;
						}
					}
					.chart_item_active {
						background-color: rgba(0, 0, 0, .6);
						color: #fff;
						border-color: rgba(0, 0, 0, .6)!important;
					}
				}
			}
		}
		.progress_box {
			box-shadow: 0 0 20rpx 2rpx #ddd;
			border-radius: 10rpx;
		}
	}
	.triangle_color {
		border-color: #fff!important;
	}
</style>